package graphic.dialogs;

import graphic.MainFrame;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

public abstract class AbstractDialog extends JDialog implements ActionListener, KeyListener{

	protected JPanel panel;
	
	protected JButton okButton;
	protected JButton exitButton;
	
	String title;
	String okButtonTitle;
	int width;
	int height;
	
	public AbstractDialog(String title, String okButtonTitle, int width, int height)
	{
		super(MainFrame.getInstance());
	
		this.title = title;
		this.okButtonTitle = okButtonTitle;
		this.width = width;
		this.height = height;

		this.construct();
	}

	public AbstractDialog(String title, String okButtonTitle, int width, int height, boolean startByItself)
	{
		super(MainFrame.getInstance());
	
		this.title = title;
		this.okButtonTitle = okButtonTitle;
		this.width = width;
		this.height = height;
	}
	
	public void construct()
	{
		super.setTitle(this.title);
		
		this.initDialog();
		this.createButtons(this.okButtonTitle);
		this.createPanel();
		
		super.setContentPane(this.panel);
		
		int x = ((int)super.getParent().getSize().getWidth() - (int)super.getSize().getWidth()) / 2;
		int y = ((int)super.getParent().getSize().getHeight() - (int)super.getSize().getHeight()) / 2;
		super.setLocation(x, y);
		
		super.setVisible(true);
		super.pack();
	}

	public void createButtons(String okButton)
	{
		this.okButton = new JButton(okButton);
		this.exitButton = new JButton("Exit");
		
		this.okButton.addActionListener(this);
		this.exitButton.addActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == okButton)
		{
			if(this.checkOkFunction())
				this.okFunction();
		} else
			this.exitFunction();
	}

	public void exitFunction(){ this.dispose(); }

	public abstract void createPanel();
	public abstract void okFunction();
	public abstract boolean checkOkFunction();
	
	// Override if necessary
	public void initDialog(){}
	
	public JPanel getPanel() {
		return panel;
	}

	public JButton getOkButton() {
		return okButton;
	}

	public JButton getExitButton() {
		return exitButton;
	}

	public void setPanel(JPanel panel) {
		this.panel = panel;
	}

	public void setOkButton(JButton okButton) {
		this.okButton = okButton;
	}

	public void setExitButton(JButton exitButton) {
		this.exitButton = exitButton;
	}
	
	@Override
	public void keyPressed(KeyEvent arg0) {}

	@Override
	public void keyReleased(KeyEvent arg0) {}

	@Override
	public void keyTyped(KeyEvent e)
	{
		if(e.getKeyCode() == e.VK_ESCAPE)
			AbstractDialog.this.dispose();
	}	
}
